package com.heima.wemedia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.heima.common.aliyun.GreenImageScan;
import com.heima.common.aliyun.GreenTextScan;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.dtos.ArticleDto;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.pojos.WmChannel;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmChannelMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.mapper.WmUserMapper;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.jbf.apis.article.IArticleClient;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WmNewsAutoScanServiceImpl implements WmNewsAutoScanService {

    @Autowired
    private WmNewsMapper wmNewsMapper;

    @Autowired
    private GreenTextScan greenTextScan;

    @Autowired
    private GreenImageScan greenImageScan;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private IArticleClient iArticleClient;

    @Autowired
    private WmChannelMapper channelMapper;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private WmSensitiveMapper wmSensitiveMapper;



    @Override
    @Transactional
    @Async
    public void autoScanWmNews(Integer id) throws Exception {
        Thread.sleep(1000);
        //查询自媒体文章
        WmNews wmNews = wmNewsMapper.selectById(id);
        if (wmNews==null){
            throw new RuntimeException("当前文章不存在");
        }
        //从参数中拿到图片和文本信息
        Map<String, Object> map=getContentAndImage(wmNews);

        if (wmNews.getStatus()==1){
            //阿里云文本内容校验
            String text = (String) map.get("text");
            Boolean textFlag= handleTextScan(text,wmNews);
            if (!textFlag){
                return;
            }
            Boolean sensiTiveFlag=handleSensiTiveTextScan(text,wmNews);
            if (!sensiTiveFlag){
                return;
            }

            //阿里云图片内容校验
            List<String> image = (List<String>)map.get("image");
            Boolean imageFlag=handleImageScan(image,wmNews);
            if (!imageFlag){
                return;
            }
            //审核成功，保存app端相关文章数据
            ResponseResult responseResult = saveAppArticle(wmNews);
            if (!responseResult.getCode().equals(200)){
                throw new RuntimeException("保存app端相关数据失败");
            }
            Long articleId = (Long) responseResult.getData();
            wmNews.setArticleId(articleId);
            wmNews.setStatus((short) 9);
            wmNews.setReason("审核成功");
            wmNewsMapper.updateById(wmNews);

        }


    }

    private Boolean handleSensiTiveTextScan(String text,WmNews wmNews) {
        List<WmSensitive> wmSensitives = wmSensitiveMapper.selectList(null);
        List<String> sensitiveList = wmSensitives.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
        //初始化敏感词库
        SensitiveWordUtil.initMap(sensitiveList);
        //查看文章中是否包含了敏感词
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        Boolean flag=true;
        if (map.size()>0){
            wmNews.setStatus((short) 2);
            wmNews.setReason("内容中存在敏感词,不允许发布");
            wmNewsMapper.updateById(wmNews);
            flag=false;
        }
        return flag;
    }

    private ResponseResult saveAppArticle(WmNews wmNews) {
        ArticleDto articleDto = new ArticleDto();
        BeanUtils.copyProperties(wmNews,articleDto);
        articleDto.setAuthorId(wmNews.getUserId().longValue());
        articleDto.setLayout(wmNews.getType());
        WmChannel wmChannel = channelMapper.selectById(wmNews.getChannelId());
        if (wmChannel!=null){
            articleDto.setChannelName(wmChannel.getName());
        }
        WmUser wmUser = wmUserMapper.selectById(wmNews.getUserId());
        if (wmUser!=null){
            articleDto.setAuthorName(wmUser.getName());
        }

        if (wmNews.getArticleId()!=null){
            articleDto.setId(wmNews.getArticleId());
        }
        articleDto.setCreatedTime(new Date());
        ResponseResult responseResult = iArticleClient.saveArticle(articleDto);
        return responseResult;

    }

    private Boolean handleImageScan(List<String> image, WmNews wmNews) throws Exception {
//        List<String> list = Arrays.asList(image);
        Boolean flag=true;
        for (String imageItem : image) {
            byte[] bytes = fileStorageService.downLoadFile(imageItem);
            Map map = greenImageScan.greeImageScan(bytes);
            String suggestion = (String) map.get("suggestion");
            if ("pass".equals(suggestion)){
                wmNews.setStatus((short) 8);
                wmNewsMapper.updateById(wmNews);
            }else {

                String result = (String) map.get("result");
                wmNews.setStatus((short) 2);
                wmNews.setReason("图片违规不允许通过！");
                flag=false;
            }
        }
        return flag;
    }

    private Boolean handleTextScan(String text, WmNews wmNews) throws Exception {

        if (StringUtils.isBlank(text)){
            return false;
        }
        Map map=null;
        try{
            map = greenTextScan.greeTextScan(text);
        }catch (Exception e){
            e.printStackTrace();
            return false;
        }

        String suggestion = (String) map.get("suggestion");
        Boolean flag=true;
        if ("pass".equals(suggestion)){
            wmNews.setStatus((short) 8);
            wmNewsMapper.updateById(wmNews);//修改状态
        }else {
            String reason = (String) map.get("reason");
            wmNews.setStatus((short) 2);
            wmNews.setReason("有违规内容，不允许通过");
            wmNewsMapper.updateById(wmNews);
            flag=false;
        }
        return flag;

    }

    private Map<String, Object> getContentAndImage(WmNews wmNews) {
        String content = wmNews.getContent();

        List<String> images=new ArrayList<>();
        StringBuilder stringBuilder=new StringBuilder();
        if (StringUtils.isNotBlank(content)){
            List<Map> maps = JSON.parseArray(content, Map.class);
            for (Map map : maps) {
                if (map.get("type").equals("text")){
                    stringBuilder.append(map.get("value"));
                }

                if (map.get("type").equals("image")){
                    images.add(map.get("value").toString());
                }
            }

        }

        //存入封面图片的数据
        if (StringUtils.isNotBlank(wmNews.getImages())){
            String[] imageArr = wmNews.getImages().split(",");
            images.addAll(Arrays.asList(imageArr));
        }

        Map<String,Object> map=new HashMap<>();
        map.put("text",stringBuilder.toString());
        map.put("image",images);

        return map;
    }
}
